package com.atguigu.srb.sms.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.atguigu.srb.core.util.RandomUtils;
import com.atguigu.srb.sms.service.SmsService;
import com.atguigu.srb.sms.util.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class SmsServiceImpl implements SmsService {
    @Autowired
    RedisTemplate redisTemplate;

    @Transactional
    @Override
    public void sendMsg(String mobile) {
        // 测试调用短信api
        DefaultProfile defaultProperty = DefaultProfile.getProfile(SmsProperties.REGIONID, SmsProperties.KEYID, SmsProperties.KEYSECRET);
        IAcsClient iAcsClient = new DefaultAcsClient(defaultProperty);

        // 请求接口参数
        CommonRequest commonRequest = new CommonRequest();
        commonRequest.setSysMethod(MethodType.POST);
        commonRequest.setSysDomain("dysmsapi.aliyuncs.com");
        commonRequest.setSysVersion("2017-05-25");// 接口版本
        commonRequest.setSysAction("SendSms");// 接口名
        commonRequest.putQueryParameter("PhoneNumbers", mobile);
        String signName = SmsProperties.SIGNNAME;
        commonRequest.putQueryParameter("SignName", signName);
        commonRequest.putQueryParameter("TemplateCode", SmsProperties.TEMPLATECODE);

        // 也使用json工具制作参数
        Map<String, String> map = new HashMap<>();
        String sixBitRandom = RandomUtils.getSixBitRandom();

        // 将验证码存入缓存
        redisTemplate.opsForValue().set("srb:sms:code:" + mobile, sixBitRandom);
        map.put("code", sixBitRandom);
        String json = JSON.toJSONString(map);
        log.info("短信验证码code---->"+map);
        commonRequest.putQueryParameter("TemplateParam", json);

        // 发送
        CommonResponse commonResponse = null;
        try {
            // 调用发送短信功能
            commonResponse = iAcsClient.getCommonResponse(commonRequest);
            System.out.println("commonResponse = " + commonResponse);
            // 捕捉异常信息
        } catch (ClientException e) {
            e.printStackTrace();
        }


    }

    @Override
    public void sendMessage(String mobile, String templatecode, Map<String, Object> param) {
       // this.sendMsg(mobile);
        String code = (String) param.get("code");
        log.info(mobile + "--->消息消费了,短信验证码--->" + code + "\n templatecode--->" + templatecode);
        System.out.println("templatecode = " + templatecode);
    }


}
